<template>
  <div class="un-flow-user-setter">
    <el-divider direction="horizontal" content-position="center"
      >用户选择设置</el-divider
    >
    <el-form-item label="用户类型">
      <el-select
        v-model="typeCodes"
        multiple
        clearable
        style="width: 100%"
        @change="onTypeChange"
      >
        <el-option
          v-for="dict in ruleTypeList"
          :key="parseInt(dict.value)"
          :label="dict.label"
          :value="parseInt(dict.value)"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script>
import { DICT_TYPE, getDictDatas } from "@/utils/dict";

export default {
  name: "UnFlowUserSetter",
  props: {
    activeData: Object,
  },
  data() {
    return {
      typeCodes: [],
      // ruleTypeList 包含labelCode
      ruleTypeList: getDictDatas(DICT_TYPE.BPM_TASK_ASSIGN_RULE_TYPE),
      // 配置字典中，设置了对应 labelCode 要调用的接口API地址
      ruleTypeConfig: getDictDatas(DICT_TYPE.PLUGIN_CONFIG_FLOW_USER),
      // 设置 ruleType 对应的数据类型
      typeConfigMap: {
        10: {
          label: "",
          value: "",
          labelCode: "",
          api: "",
          limit: 0, // 为0不限制
        },
        // 上面的映射关系需要从接口获取，才能做到不动代码，自由扩展
      },
    };
  },
  watch: {
    'activeData.__config__.renderKey': {
      handler(val, oldVal) {
        // 当前在切换不同的用户选择组件，需要重置选项
        if (val !== oldVal) {
          this.setTypeToOptions();
        }
      }
    }
  },
  created() {
    this.setTypeToOptions();
  },
  methods: {
    setTypeToOptions() {
      const ruleConfig = {};
      const typeCodes = [];
      for (let i = 0; i < this.ruleTypeConfig.length; i++) {
        const { labelCode, value } = this.ruleTypeConfig[i];
        ruleConfig[labelCode] = value;
      }
      const typeConfigMap = {};
      for (let i = 0; i < this.ruleTypeList.length; i++) {
        const { label, value, labelCode } = this.ruleTypeList[i];
        const typeConfig = {
          label,
          value,
          labelCode,
          api: ruleConfig[labelCode],
          limit: 0,
        };
        // 用户目前设置为限制选择一个
        if (labelCode === "user") {
          typeConfig.limit = 1;
        }
        typeConfigMap[value] = typeConfig;
        typeCodes.push(parseInt(value));
      }
      this.typeConfigMap = typeConfigMap;
      // 已经设置了类型列表，则初始化就是它，否则是全部的类型
      if (!this.activeData.typeList.length) {
        this.typeCodes = typeCodes;
        this.onTypeChange(typeCodes);
      } else {
        this.typeCodes = this.activeData.typeList.map(({ value }) => parseInt(value));
      }
    },
    onTypeChange(typeCodes) {
      const typeList = [];
      for (let i = 0; i < typeCodes.length; i++) {
        const code = typeCodes[i];
        if (this.typeConfigMap[code]) {
          typeList.push({ ...this.typeConfigMap[code] });
        }
      }
      this.$set(this.activeData, "typeList", typeList);
    },
  },
};
</script>

<style lang="scss"></style>
